package com.hxh.readwrite;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/9/10 22:05
 * 读写锁 Demo
 */
public class ReadWriteLockDemo {

    public static void main(String[] args) throws InterruptedException {
        MyCaChe myCaChe = new MyCaChe();
        // 创建线程放数据
        for (int i = 1; i <= 5; i++) {
            final int num = 1;
            new Thread(() -> {
                myCaChe.put(num + "", num + "");
            }, String.valueOf(i)).start();
        }
        TimeUnit.MICROSECONDS.sleep(300);
        // 创建线程读数据
        for (int i = 1; i <= 5; i++) {
            final int num = 1;
            new Thread(() -> {
                myCaChe.get(num + "");
            }, String.valueOf(i)).start();
        }
    }
}

// 资源类
class MyCaChe {

    private volatile Map<String, Object> map = new HashMap<>();

    // 创建读写锁
    private ReadWriteLock rwLock = new ReentrantReadWriteLock();

    // 模拟写操作
    public void put(String key, Object value) {
        // 添加写锁
        rwLock.writeLock().lock();
        System.out.println(Thread.currentThread().getName() + ", 正在写" + key);
        // 暂停
        try {
            TimeUnit.MICROSECONDS.sleep(300);
            // 放数据
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + ", 写完毕" + key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放锁
            rwLock.writeLock().unlock();
        }
    }

    // 模拟读操作
    public Object get(String key) {
        // 添加读锁
        rwLock.readLock().lock();
        Object result = null;
        System.out.println(Thread.currentThread().getName() + ", 正在读" + key);
        // 暂停
        try {
            TimeUnit.MICROSECONDS.sleep(300);
            // 放数据
            result = map.get(key);
            System.out.println(Thread.currentThread().getName() + ", 读完毕" + key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rwLock.readLock().unlock();
        }
        return result;
    }
}
